// validation functions.
function validateEmail() {
	var $emailField = $(".authentication .email");
    var isValid = false;
    var title = "";
    
	if ("" == $emailField.val()) {
		// required.
		title = "Email is required!";
	} else if (! $emailField.val().match(/^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/)) {
		// invalid email.
		title = "Please enter a valid email address!";
	} else {
		// valid email.
		title = "";
		isValid = true;
	}

	$emailField.attr("data-original-title", title);
	
	if ("" == title) {
		$emailField.tooltip("hide")
	} else {
		$emailField.tooltip("show");
	}
	
	return isValid;
}

function validateName() {
	var $nameField = $(".authentication .name");
	var isValid = false;
	var title = "";
	
	if ("" == $nameField.val()) {
		// required.
		title = "Name is required!";
	} else {
		// name entered.
		title = "";
		isValid = true;
	}
	
	$nameField.attr("data-original-title", title);
	
	if ("" == title) {
		$nameField.tooltip("hide")
	} else {
		$nameField.tooltip("show");
	}
	
	return isValid;
}

function validatePassword() {
	var $passField = $(".authentication input[type=password]");
	var isValid = false;
	var title = "";
	
	if ("" == $passField.val()) {
		// required.
		title = "Password is required!";
	} else {
		// name entered.
		title = "";
		isValid = true;
	}
	
	$passField.attr("data-original-title", title);
	
	if ("" == title) {
		$passField.tooltip("hide")
	} else {
		$passField.tooltip("show");
	}
	
	return isValid;
}

function validate() {
	var bool1 = validateName();
	var bool2 = validateEmail();
	var bool3 = validatePassword();
	return bool1 && bool2 && bool3;
}

$(document).ready(function() {
	// set tooltips.
	$("input[rel=tooltip]").tooltip({
		placement: "right",
		trigger: "manual"
	});
	
	// registration.
	$(".authentication .email").live("change", validateEmail)
							   .live("blur", validateEmail);
	$(".authentication .name").live("change", validateName)
	   						  .live("blur", validateName);
	$(".authentication input[type=password]").live("change", validatePassword)
											 .live("blur", validatePassword)
		  .live("blur", validateName);
	$("form.registration").submit(function() {
		if (! validate()) {
			return false;
		}
	});
	
	// tagging system.
	$("#tags,.tags").tagedit({
		allowEdit: false,
		autocompleteOptions: {
			minLength: 2,
			source: function (request, response) {
				$.getJSON(getURL("/tag/search?term=" + request.term), function(data) {
					var list = [];
					$.each(data, function(i, v) {
						if (! v.name) {
							return;
						}
						var item = {
							label: v.name + " - " + v.type[0].name,
							value: v.name,
							id: v.guid
						};
						list.push(item);
					});
					response(list);
				});
			},
			select: function (e, ui) {
				$(this).val(ui.item.value).trigger('transformToTag', [ui.item.id]);
				return false;
			}
		}
	});
});